package com.xiaoshuidi.cloud.module.report.service.finance;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.oss.core.OosFileService;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.report.controller.finance.vo.*;
import com.xiaoshuidi.cloud.module.report.convert.finance.CollectInAdvanceConvert;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.CollectInAdvanceDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.CollectInAdvanceMapper;
import com.xiaoshuidi.cloud.module.report.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.report.framework.security.config.ConfigValues;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.List;


@Service
@RequiredArgsConstructor
@Slf4j
public class CollectInAdvanceServiceImpl implements CollectInAdvanceService {

    private final CollectInAdvanceMapper collectInAdvanceMapper;
    private final OosFileService oosFileService;
    private final ConfigValues configValues;

    @Override
    public CollectInAdvanceDO selectRentAdvanceByContractIdAndMonth(Long contractId) {
        return collectInAdvanceMapper.selectRentAdvanceByContractIdAndMonth(contractId);
    }

    @Override
    public void batchInsert(List<CollectInAdvanceDO> list){
        collectInAdvanceMapper.insertBatch(list);
    }
    @Override
    public void batchUpdate(List<CollectInAdvanceDO> list){
        collectInAdvanceMapper.updateBatch(list,list.size());
    }

    @Override
    public CollectInAdvancePageRespVO advancePage(CollectInAdvanceReqVO reqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        reqVO.setTenantId(loginUser.getTenantId());
        long num = collectInAdvanceMapper.countListForPage(reqVO);
        List<CollectInAdvanceDO> advanceDOList = collectInAdvanceMapper.selectListForPage(reqVO);
//        advanceRespVOS.forEach(e->{
//            List<CollectInAdvanceDO> advanceList = collectInAdvanceMapper.selectAdvancesByContractIdAndMonth(e.getContractId(), e.getStatisticsMonth());
//            List<AdvanceContractRespVO> contractList = CollectInAdvanceConvert.INSTANCE.convertDOList2AdvanceContractVOS(advanceList);
//            e.setContractList(contractList);
//        });
        CollectInAdvancePageRespVO respVO = new CollectInAdvancePageRespVO();
        if(CollectionUtils.isEmpty(advanceDOList)){
            return respVO;
        }
        List<CollectInAdvanceRespVO> advanceRespVOS = CollectInAdvanceConvert.INSTANCE.convertDOList2AdvanceVOList(advanceDOList);
        CollectInAdvanceDO collectInAdvanceDO = collectInAdvanceMapper.selectTotalAmountInMonth(reqVO);
        respVO.setTotalOpeningBalance(collectInAdvanceDO.getOpeningBalance());
        respVO.setTotalCurNewAdd(collectInAdvanceDO.getCurNewAdd());
        respVO.setTotalCurCarryFoward(collectInAdvanceDO.getCurCarryFoward());
        respVO.setTotalEndingBalance(collectInAdvanceDO.getEndingBalance());
        respVO.setTotal(num);
        respVO.setList(advanceRespVOS);
        return respVO;
    }

    @Override
    public ExportRespVO export(CollectInAdvanceReqVO req) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if(loginUser==null){
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        req.setTenantId(loginUser.getTenantId());
        //暂时不分页，当月合同数不会超过2000
        String fileName =  req.getStatisticsMonth() + "预收账款明细表.xlsx";
        String filePath = configValues.getNfsPath() + File.separator +fileName;
        ExcelWriter excelWriter = EasyExcel.write(filePath, CollectInAdvanceExportRespVO.class).build();
        WriteSheet sheet = EasyExcel.writerSheet("sheet1").build();
        List<CollectInAdvanceDO> reportDOList = collectInAdvanceMapper.selectListForExport(req);
        if(CollectionUtils.isEmpty(reportDOList)){
            throw new ServiceException(ErrorCodeConstants.ADVANCE_NOT_EXISTS);
        }
        List<CollectInAdvanceExportRespVO> list = CollectInAdvanceConvert.INSTANCE.convertDOList2AdvanceExport(reportDOList);
        excelWriter.write(list, sheet);
        excelWriter.finish();
        //上传到oos返回URL
        String url = oosFileService.oosUploadFile(new File(filePath));
        ExportRespVO resp = new ExportRespVO();
        if(url.startsWith("http:")){
            url = url.replace("http:","https:");
        }
        resp.setUrl(url);
        resp.setFileName(fileName);
        return resp;
    }

    @Override
    public List<CollectInAdvanceDO> selectDetailsInCurrentMonth(String currentMonth,List<Long> contractIds) {
        LambdaQueryWrapper<CollectInAdvanceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CollectInAdvanceDO::getStatisticsMonth, currentMonth);
        queryWrapper.in(CollectInAdvanceDO::getContractId, contractIds);
        return collectInAdvanceMapper.selectList(queryWrapper);
    }


    @Override
    public List<CollectInAdvanceDO> selectByContractId(Long contractId) {
        LambdaQueryWrapper<CollectInAdvanceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CollectInAdvanceDO::getContractId, contractId);
        return collectInAdvanceMapper.selectList(queryWrapper);
    }


}
